﻿using PLCS.App.UserAuthorization;
using PLCS.Application.Contracts.LogShowApp.Dtos;
using PLCS.Application.Contracts.MenuApp.Dtos;
using PLCS.Client.IService.LogManager;
using PLCS.Shared.Common.Constant;

using System.Reflection.Metadata;

namespace ZFGG_JTX_PLCS.App.UserAuthorization.ViewModels.Menu;

internal class MenuDetailViewModel : HostDialogViewModel
{
    private readonly IMenuService _menuService;
    private readonly IObjectMapper<UserAuthorizationModule> _objectMapper;
    private readonly IOperationLogService _logShowService;
    private MenuDto _model;

    public MenuDto Model
    {
        get { return _model; }
        set { SetProperty(ref _model, value); }
    }

    #region 父级菜单下拉选项

    private ObservableCollection<string> _canSelectParents = new ObservableCollection<string>();

    public ObservableCollection<string> CanSelectParents
    {
        get { return _canSelectParents; }
        set { SetProperty(ref _canSelectParents, value); }
    }

    public DelegateCommand DropOpenedCommand => new DelegateCommand(DropOpened);

    /// <summary>
    /// 下拉刷新
    /// </summary>
    private async void DropOpened()
    {
        var Models = await _menuService.GetListAsync();
        CanSelectParents.Clear();
        foreach (var item in Models.Where(x => string.IsNullOrEmpty(x.ViewName)))
        {
            CanSelectParents.Add(item.Title);
        }
    }

    #endregion 父级菜单下拉选项

    public override void OnDialogOpened(IDialogParameters parameters)
    {
        if (parameters.ContainsKey("Value"))
        {
            Model = parameters.GetValue<MenuDto>("Value");
            Title = "编辑";
        }
        else
        {
            Title = "新增";
            Model = new MenuDto();
        }
    }

    protected override async void Save()
    {
        try
        {
            SavebuttonIsEnabled = false;
            var menu = _objectMapper.Map<MenuDto, MenuEditDto>(Model);
            if (menu.Id != Guid.Empty)
                await _menuService.UpdateAsync(menu);
            else
                await _menuService.CreateAsync(menu);

            ShowMessage("操作成功");
            base.Save();
        }
        catch (Exception ex)
        {
            ShowMessage("操作失败");
        }
        finally { SavebuttonIsEnabled = true; }
    }

    public MenuDetailViewModel(IMenuService menuService, IObjectMapper<UserAuthorizationModule> objectMapper, IOperationLogService logShowService)
    {
        _menuService = menuService;
        this._objectMapper = objectMapper;
        this._logShowService = logShowService;
    }
}